package com.agy.filemanager.exception;

import com.agy.filemanager.toolClass.Result;
import com.agy.filemanager.toolClass.ResultUtil;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * controller 增强器
 * jpf
 */
@ControllerAdvice
public class MyControllerAdvice {
    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) { }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("website", "档案管理系统");
        model.addAttribute("fileUpload", "1E38C4238E964BDE89B7484EE40D9FCA");
        model.addAttribute("fullSearch", "1E38C4228E964BDE89B7484EE40D9FCA");
        model.addAttribute("analysis", "1E38C4218E964BDE89B7484EE40D9FCA");
        model.addAttribute("system", "1E38C4208E964BDE89B7484EE40D9FCA");

    }
    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception ex, HttpServletResponse response, HttpServletRequest request) {
        String msg = ex.getMessage()+"错误位置："+request.getRequestURI();
        return ResultUtil.error(Integer.toString(response.getStatus()),msg);
    }
    /**
     * 拦截捕捉自定义异常 CustomExceptionEntity.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = CustomExceptionEntity.class)
    public Map myErrorHandler(CustomExceptionEntity ex) {
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMessage());
        map.put("pos", ex.getPos());
        return map;
    }
}
